<template>
    <div class="app-container">
        <el-card class="">
            <!-- 搜索和筛选区域 -->
            <div>
                <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                    <el-form-item label="指令编号">
                        <el-input v-model="queryParams.instructionCode" placeholder="请输入指令编号" clearable
                            style="width: 300px" />
                    </el-form-item>

                    <el-form-item label="指令类型">
                        <el-select v-model="queryParams.instructionType" placeholder="请选择指令类型" clearable
                            style="width: 300px">
                            <el-option v-for="item in typeOptions" :key="item.dictValue" :label="item.dictLabel"
                                :value="item.dictValue" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="目标厂站">
                        <el-select v-model="queryParams.receiverStationId" placeholder="请选择目标厂站" clearable
                            style="width: 300px">
                            <el-option v-for="item in stationOptions" :key="item.dictValue" :label="item.dictLabel"
                                :value="item.dictValue" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="指令状态">
                        <el-select v-model="queryParams.instructionStatus" placeholder="请选择指令状态" clearable
                            style="width: 300px">
                            <el-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel"
                                :value="item.dictValue" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="时间范围">
                        <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                            @change="handleDateChange" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>

        <el-card class="mt-1">
            <!-- 操作按钮区域 -->
            <div>
                <el-button type="primary" @click="showAddDialog">
                    <el-icon>
                        <Plus />
                    </el-icon>新增指令
                </el-button>
                <el-button @click="handleImport">
                    <el-icon>
                        <Upload />
                    </el-icon>导入
                </el-button>
                <el-button @click="handleExport">
                    <el-icon>
                        <Download />
                    </el-icon>导出
                </el-button>
                <el-button @click="refreshData">
                    <el-icon>
                        <Refresh />
                    </el-icon>刷新
                </el-button>
            </div>
            <el-radio-group v-model="queryParams.pageType" @change="handleQuery" class=" mt-2">
                <el-radio-button label="1">全部指令</el-radio-button>
                <el-radio-button label="2">待办指令</el-radio-button>
                <el-radio-button label="3">已办指令</el-radio-button>
                <el-radio-button label="4">我的审批</el-radio-button>
                <el-radio-button label="5">我的申请</el-radio-button>
                <el-radio-button label="7">我的创建</el-radio-button>
            </el-radio-group>
            <!-- 表格区域 -->
            <el-table :data="tableData" border style="width: 100%" v-loading="loading" class=" mt-2"
                :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
                <el-table-column prop="instructionCode" label="指令编号" />
                <el-table-column prop="instructionTitle" label="指令标题" />
                <el-table-column label="指令类型">
                    <template #default="{ row }">
                        {{ getDictLabel(typeOptions, row.instructionType) }}
                    </template>
                </el-table-column>
                <el-table-column label="目标厂站">
                    <template #default="{ row }">
                        {{ getDictLabel(stationOptions, row.receiverStationId) }}
                    </template>
                </el-table-column>
                <el-table-column prop="sendTime" label="发送时间" />
                <el-table-column prop="endTime" label="截止时间" />
                <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.instructionStatus)">
                            {{ getDictLabel(statusOptions, row.instructionStatus) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="showDetailDialog(row)">详情</el-button>
                        <el-button size="small" :type="getButtonType(row.instructionStatus)"
                            @click="showHandleDialog(row)" v-if="showHandleButton(row.instructionStatus)">
                            {{ getButtonText(row.instructionStatus) }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增指令对话框 -->
        <el-dialog v-model="addDialogVisible" title="新增调度指令" width="50%" :close-on-click-modal="false">
            <el-form :model="currentInstruction" label-width="120px" :rules="rules" ref="addFormRef">
                <el-form-item label="指令类型" prop="instructionType">
                    <el-select v-model="currentInstruction.instructionType" placeholder="请选择指令类型" style="width: 100%">
                        <el-option v-for="item in typeOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="目标厂站" prop="receiverStationId">
                    <el-select v-model="currentInstruction.receiverStationId" placeholder="请选择目标厂站" style="width: 100%">
                        <el-option v-for="item in stationOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="指令标题" prop="instructionTitle">
                    <el-input v-model="currentInstruction.instructionTitle" placeholder="请输入指令标题" />
                </el-form-item>
                <el-form-item label="指令内容" prop="instructionContent">
                    <el-input v-model="currentInstruction.instructionContent" type="textarea" :rows="4"
                        placeholder="请输入指令内容" />
                </el-form-item>
                <el-form-item label="截止时间" prop="endTime">
                    <el-date-picker v-model="currentInstruction.endTime" type="datetime" placeholder="选择截止时间"
                        style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="优先级" prop="priority">
                    <el-select v-model="currentInstruction.priority" placeholder="请选择优先级" style="width: 100%">
                        <el-option v-for="item in priorityOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="调度员" prop="dispatcherIds">
                    <el-select v-model="currentInstruction.dispatcherIds" multiple placeholder="请选择调度员"
                        style="width: 100%">
                        <el-option v-for="item in dispatcherOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="附件">
                    <!-- <el-upload action="" :file-list="fileList" :auto-upload="false" :on-change="handleFileChange"
                        multiple>
                        <el-button type="primary">选择文件</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持上传图片、文档等附件，单个文件不超过10MB
                            </div>
                        </template>
                    </el-upload> -->

                    <UploadFile v-model:file-ids="currentInstruction.files" type="file" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAdd">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 指令详情对话框 -->
        <el-dialog v-model="detailDialogVisible" :title="detailDialogTitle" width="60%" :close-on-click-modal="false">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="指令编号">{{ currentInstruction.instructionCode }}</el-descriptions-item>
                <el-descriptions-item label="指令标题">{{ currentInstruction.instructionTitle }}</el-descriptions-item>
                <el-descriptions-item label="指令类型">{{ getDictLabel(typeOptions, currentInstruction.instructionType)
                    }}</el-descriptions-item>
                <el-descriptions-item label="目标厂站">{{ getDictLabel(stationOptions, currentInstruction.receiverStationId)
                    }}</el-descriptions-item>
                <el-descriptions-item label="发送时间">{{ currentInstruction.sendTime }}</el-descriptions-item>
                <el-descriptions-item label="截止时间">{{ currentInstruction.endTime }}</el-descriptions-item>
                <el-descriptions-item label="优先级">{{ getDictLabel(priorityOptions, currentInstruction.priority)
                    }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getStatusTagType(currentInstruction.instructionStatus)">
                        {{ getDictLabel(statusOptions, currentInstruction.instructionStatus) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="指令内容" :span="2">
                    {{ currentInstruction.instructionContent }}
                </el-descriptions-item>
                <el-descriptions-item label="附件" :span="2">
                    <div v-for="file in currentInstruction.fileVoList" :key="file.fileId" class="file-item">
                        <el-link type="primary" :href="file.filePath" target="_blank">
                            {{ file.originalFileName }}
                        </el-link>
                        <span class="file-size">({{ formatFileSize(file.fileSize) }})</span>
                    </div>
                </el-descriptions-item>
            </el-descriptions>

            <el-divider content-position="left">处理记录</el-divider>
            <el-timeline>
                <el-timeline-item v-for="(log, index) in currentInstruction.logs" :key="index"
                    :timestamp="log.operationTime" placement="top">
                    <el-card>
                        <h4>{{ log.operationType }} - {{ log.userName }}</h4>
                        <p v-if="log.remark">备注: {{ log.remark }}</p>
                    </el-card>
                </el-timeline-item>
            </el-timeline>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 处理指令对话框 -->
        <el-dialog v-model="handleDialogVisible" title="处理调度指令" width="50%" :close-on-click-modal="false">
            <el-form :model="handleForm" label-width="120px" :rules="handleRules" ref="handleFormRef">
                <el-form-item label="操作类型" prop="instructionStatus" v-if="handleFormRow.instructionStatus == '待审批'">
                    <el-select v-model="handleForm.instructionStatus" placeholder="请选择操作类型" style="width: 100%">
                        <el-option label="已审批" value="已审批" />
                        <el-option label="已驳回" value="已驳回" />
                    </el-select>
                </el-form-item>
                <el-form-item label="审核人" prop="approvalId" v-if="handleFormRow.instructionStatus == '已完成'">
                    <el-select v-model="handleForm.approvalId" placeholder="请选择调度员" style="width: 100%">
                        <el-option v-for="item in dispatcherOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="操作详情" prop="remark">
                    <el-input v-model="handleForm.remark" type="textarea" :rows="4" placeholder="请输入处理备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmHandle">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog v-model="importDialogVisible" title="导入调度指令" width="40%" :close-on-click-modal="false">
            <el-upload class="upload-demo" drag action="" :auto-upload="false" :on-change="handleImportFileChange"
                :file-list="importFileList" accept=".xlsx,.xls">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        请上传Excel文件，文件大小不超过10MB
                        <el-button type="text" @click="downloadTemplate">下载模板</el-button>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="importDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmImport">导入</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile'
import {
    getInstructionTypeList,
    getInstructionStatusList,
    getReceiverStationList,
    getPriorityList,
    getDispatcherList,
    getDispatchInstructionList,
    addDispatchInstruction,
    handleDispatchInstruction,
    getDispatchInstructionDetail,
    exportDispatchInstruction,
    importDispatchInstruction,
    downloadImportTemplate
} from '@/api/dispatch/affair/distpachCommand'

// 加载状态
const loading = ref(false)

// 下拉选项数据
const typeOptions = ref([])
const statusOptions = ref([])
const stationOptions = ref([])
const priorityOptions = ref([])
const dispatcherOptions = ref([])

// 表格数据
const tableData = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    instructionCode: '',
    instructionType: '',
    receiverStationId: '',
    instructionStatus: '',
    startTime: '',
    endTime: '',
    pageType: '1'
})
// 按钮显示逻辑
const showHandleButton = (status) => {
  return !['已审批', '已驳回'].includes(status);
};

// 按钮文本映射
const getButtonText = (status) => {
  const statusMap = {
    '待处理': '处理',
    '处理中': '完成',
    '提交审批': '选择审批人',
    '已完成': '提交审批', 
    '待审批': '审批'
  };
  return statusMap[status] || '处理';
};

// 按钮类型映射
const getButtonType = (status) => {
  const typeMap = {
    '待处理': 'primary',
    '处理中': 'success',
    '提交审批': 'warning',
    '已完成': 'primary',
    '待审批': 'danger'
  };
  return typeMap[status] || 'primary';
};
// 日期范围
const dateRange = ref([])

// 当前操作的指令
const currentInstruction = reactive({
    instructionId: '',
    instructionCode: '',
    instructionTitle: '',
    instructionType: '',
    receiverStationId: '',
    instructionContent: '',
    endTime: '',
    priority: '',
    dispatcherIds: [],
    fileVoList: [],
    logs: [],
    files: ''
})

const handleFormRow = reactive({})
// 处理表单
const handleForm = reactive({
    instructionId: '',
    instructionStatus: '',
    remark: '',
    approvalId: ''
})

// 文件列表
const fileList = ref([])
const importFileList = ref([])
const importFile = ref(null)

// 对话框控制
const addDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const handleDialogVisible = ref(false)
const importDialogVisible = ref(false)
const detailDialogTitle = ref('指令详情')

// 表单引用
const addFormRef = ref(null)
const handleFormRef = ref(null)

// 表单验证规则
const rules = reactive({
    instructionType: [
        { required: true, message: '请选择指令类型', trigger: 'change' }
    ],
    receiverStationId: [
        { required: true, message: '请选择目标厂站', trigger: 'change' }
    ],
    instructionTitle: [
        { required: true, message: '请输入指令标题', trigger: 'blur' }
    ],
    instructionContent: [
        { required: true, message: '请输入指令内容', trigger: 'blur' }
    ],
    endTime: [
        { required: true, message: '请选择截止时间', trigger: 'change' }
    ],
    priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
    ],
    dispatcherIds: [
        { required: true, message: '请选择调度员', trigger: 'change' }
    ]
})

const handleRules = reactive({
    instructionStatus: [
        { required: true, message: '请选择操作类型', trigger: 'change' }
    ],
    remark: [
        { required: true, message: '请输入处理备注', trigger: 'blur' }
    ]
})

// 根据字典值获取标签
const getDictLabel = (options, value) => {
    if (!options || !value) return ''
    const item = options.find(item => item.dictValue === value)
    return item ? item.dictLabel : value
}

// 获取状态标签类型
const getStatusTag = (status) => {
    switch (status) {
        case 'completed': return 'success'
        case 'processing': return 'warning'
        case 'pending': return 'danger'
        default: return ''
    }
}

// 格式化文件大小
const formatFileSize = (size) => {
    if (size < 1024) {
        return size + 'KB'
    } else {
        return (size / 1024).toFixed(2) + 'MB'
    }
}

// 初始化数据
const initData = async () => {
    try {
        loading.value = true

        // 获取下拉选项数据
        const [
            typeRes,
            statusRes,
            stationRes,
            priorityRes,
            dispatcherRes
        ] = await Promise.all([
            getInstructionTypeList(),
            getInstructionStatusList(),
            getReceiverStationList(),
            getPriorityList(),
            getDispatcherList()
        ])

        typeOptions.value = typeRes.data
        statusOptions.value = statusRes.data
        stationOptions.value = stationRes.data
        priorityOptions.value = priorityRes.data
        dispatcherOptions.value = dispatcherRes.data

        // 获取指令列表
        await fetchInstructionList()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    } finally {
        loading.value = false
    }
}

// 获取指令列表
const fetchInstructionList = async () => {
    try {
        loading.value = true
        const res = await getDispatchInstructionList(queryParams)
        tableData.value = res.rows
        total.value = res.total
    } catch (error) {
        console.error('获取指令列表失败:', error)
        ElMessage.error('获取指令列表失败')
    } finally {
        loading.value = false
    }
}

// 处理日期范围变化
const handleDateChange = (val) => {
    if (val && val.length === 2) {
        queryParams.startTime = val[0]
        queryParams.endTime = val[1]
    } else {
        queryParams.startTime = ''
        queryParams.endTime = ''
    }
}

// 处理查询
const handleQuery = () => {
    queryParams.pageNum = 1
    fetchInstructionList()
}

// 重置查询条件
const resetQuery = () => {
    dateRange.value = []
    queryParams.instructionCode = ''
    queryParams.instructionType = ''
    queryParams.receiverStationId = ''
    queryParams.instructionStatus = ''
    queryParams.startTime = ''
    queryParams.endTime = ''
    handleQuery()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
    queryParams.pageSize = val
    fetchInstructionList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
    queryParams.pageNum = val
    fetchInstructionList()
}

// 显示新增对话框
const showAddDialog = () => {
    resetCurrentInstruction()
    addDialogVisible.value = true
}

// 重置当前指令
const resetCurrentInstruction = () => {
    currentInstruction.instructionId = ''
    currentInstruction.instructionCode = ''
    currentInstruction.instructionTitle = ''
    currentInstruction.instructionType = ''
    currentInstruction.receiverStationId = ''
    currentInstruction.instructionContent = ''
    currentInstruction.endTime = ''
    currentInstruction.priority = ''
    currentInstruction.dispatcherIds = []
    currentInstruction.fileVoList = []
    fileList.value = []
}

// 显示详情对话框
const showDetailDialog = async (row) => {
    try {
        loading.value = true
        const res = await getDispatchInstructionDetail(row.instructionId)
        Object.assign(currentInstruction, res.data)
        detailDialogTitle.value = `指令详情 - ${currentInstruction.instructionTitle}`
        detailDialogVisible.value = true
    } catch (error) {
        console.error('获取指令详情失败:', error)
        ElMessage.error('获取指令详情失败')
    } finally {
        loading.value = false
    }
}

// 显示处理对话框
const showHandleDialog = (row) => {
    handleForm.instructionId = row.instructionId
    handleFormRow.instructionStatus = row.instructionStatus;
    handleForm.remark = ''
    handleDialogVisible.value = true
}

// 处理导入文件变化
const handleImportFileChange = (file) => {
    importFile.value = file.raw
}

// 确认新增
const confirmAdd = async () => {
    try {
        await addFormRef.value.validate()
        console.log(currentInstruction);


        await addDispatchInstruction(currentInstruction)
        ElMessage.success('新增指令成功')
        addDialogVisible.value = false
        fetchInstructionList()
    } catch (error) {
        console.error('新增指令失败:', error)
        if (error.message) {
            ElMessage.error(error.message)
        }
    }
}

// 确认处理
const confirmHandle = async () => {
    try {
        await handleFormRef.value.validate()

        await handleDispatchInstruction(handleForm)
        ElMessage.success('处理指令成功')
        handleDialogVisible.value = false
        fetchInstructionList()
    } catch (error) {
        console.error('处理指令失败:', error)
        if (error.message) {
            ElMessage.error(error.message)
        }
    }
}

// 处理导出
const handleExport = async () => {
    try {
        loading.value = true
        const res = await exportDispatchInstruction(queryParams)
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '调度指令列表.xlsx'
        link.click()
        URL.revokeObjectURL(link.href)
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    } finally {
        loading.value = false
    }
}

// 处理导入
const handleImport = () => {
    importFileList.value = []
    importFile.value = null
    importDialogVisible.value = true
}

// 下载模板
const downloadTemplate = async () => {
    try {
        const res = await downloadImportTemplate()
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '调度指令导入模板.xlsx'
        link.click()
        URL.revokeObjectURL(link.href)
    } catch (error) {
        console.error('下载模板失败:', error)
        ElMessage.error('下载模板失败')
    }
}

// 确认导入
const confirmImport = async () => {
    if (!importFile.value) {
        ElMessage.warning('请先选择文件')
        return
    }

    try {
        loading.value = true
        const formData = new FormData()
        formData.append('file', importFile.value)

        await importDispatchInstruction(formData)
        ElMessage.success('导入成功')
        importDialogVisible.value = false
        fetchInstructionList()
    } catch (error) {
        console.error('导入失败:', error)
        if (error.message) {
            ElMessage.error(error.message)
        }
    } finally {
        loading.value = false
    }
}

// 刷新数据
const refreshData = () => {
    fetchInstructionList()
    ElMessage.success('刷新成功')
}

// 初始化
onMounted(() => {
    initData()
})
</script>

<style scoped>
.app-container {}


.operation-buttons {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.file-item {
    margin-bottom: 8px;
}

.file-size {
    margin-left: 8px;
    color: #909399;
}

.upload-demo {
    text-align: center;
}

.el-upload__tip {
    margin-top: 10px;
}
</style>